package com.example.multithread.no1116;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ConditionZeroEvenOdd {

    private int n;
    private volatile int start = 1;

    private volatile int who;
    private Lock lock = new ReentrantLock();
    private Condition zero = lock.newCondition();
    private Condition even = lock.newCondition();
    private Condition odd = lock.newCondition();

    public ConditionZeroEvenOdd(int n) {
        this.n = n;
    }

    public static void main(String[] args) {
        ConditionZeroEvenOdd zeroEvenOdd = new ConditionZeroEvenOdd(6);
        new Thread(() -> {
            try {
                zeroEvenOdd.zero();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                zeroEvenOdd.even();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                zeroEvenOdd.odd();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

    public void zero() throws InterruptedException {
        lock.lock();
        try {
            while (start <= n) {
                if(who!=0){
                    zero.await();
                }
                System.out.print(0);
                if(start%2 == 0){
                    who = 2;
                    even.signal();
                } else {
                    who = 1;
                    odd.signal();
                }
                zero.await();
            }
            odd.signal();
            even.signal();
        } finally {
            lock.unlock();
        }
    }

    /**
     * 偶数
     * @throws InterruptedException
     */
    public void even() throws InterruptedException {

        lock.lock();
        try {
            while (start <= n) {
                if (who!=2) {
                    even.await();
                } else {
                    System.out.print(start++);
                    who=0;
                    zero.signal();
                }
            }
        } finally {
            lock.unlock();
        }
    }

    /**
     * 奇数
     * @throws InterruptedException
     */
    public void odd() throws InterruptedException {

        lock.lock();
        try {
            while (start <= n) {
                if (who!=1) {
                    odd.await();
                } else {
                    System.out.print(start++);
                    who=0;
                    zero.signal();
                }
            }
        } finally {
            lock.unlock();
        }
    }
}
